<?php


namespace Frieza\Modules\Search\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\SelectParams\SelectParamsOptions;
use Doraemon\service\Photo\SelectParams as photoSelectParams;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;


class SelectConfigController extends Controller
{
    const PAGE_SIZE = 20;

    private static $config = [];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        if (!self::$config) {
//            self::$config = photoSelectParams::getConfig();
            self::$config = photoSelectParams::getConfigV2();
        }
    }

    /**
     * 类型列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content)
    {
        $list = [];
        foreach (self::$config as $type => $row) {
            $list[] = [
                'id' => $type,
                'name' => $row['name']
            ];
        }
        $gridModel = new pGridDataModel($list);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->tools(function (Grid\Tools $tool) {
                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增', '', url('/admin/search/select/create')));
            });
            $grid->column('id')->sort();
            $grid->column('name', '分类');
            $grid->disableActions();
        });

        $list = $listGrid->render();
        $tab = new Tab();
        $tab->add('选项类别', $list);
        foreach (self::$config as $type => $row) {
            $tab->addLink($row['name'], '/admin/search/select/' . $type . '/option');
        }
        return $content
            ->header('看图筛选条件管理')
            ->breadcrumb(
                ['text' => '看图筛选条件']
            )
            ->body($tab);
    }

    /**
     * 选项列表
     * @param Request $request
     * @param Content $content
     * @param $type
     * @return Content
     */
    public function option(Request $request, Content $content, $type)
    {
        $list = self::$config;
        $info = $list[$type];
        $optionList = [];
        $key = $list[$type]['key'];
        foreach ($info['options'] as $row) {
            $optionList[] = [
                'id' => $row['id'],
                'option_id' => $row['options_id'] ?? '',
                'key' => $key,
                'value' => $row['value'],
                'name' => $row['name'],
                'relation_list' => $row['relation_list'] ? json_decode($row['relation_list'], true) : [],
            ];
        }
        $gridModel = new pGridDataModel($optionList);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($type, $list) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disableCreateButton();
            if ($type != photoSelectParams::TYPE_SCOPE_AUTH) {
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增', '', url('/admin/search/select/create')));
                });
            }
            unset($list[$type]);
            unset($list[photoSelectParams::TYPE_SCOPE_AUTH]);

            $grid->column('id')->hide();
            $grid->column('option_id')->sort();
            $grid->column('name', '筛选词');

//            $grid->disablePagination();
            if ($type == photoSelectParams::TYPE_SCOPE_AUTH) {
                $grid->disableActions();
            }else {
                  //暂时不增加关联词功能
//                $grid->column('relation_list', '关联词')->relationSelect($list);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    if ($actions->row->value == 'all' || $actions->row->key == 'user_type') {
                        $actions->disableDelete();
                    }
                });
            }
            $grid->disablePagination();
        });
        $tab = new Tab();
        $tab->addLink('选项类别', '/admin/search/select/index');
        foreach (self::$config as $configType => $row) {
            if ($type == $configType) {
                $tab->add($row['name'], $listGrid->render(), true);
            } else {
                $tab->addLink($row['name'], '/admin/search/select/' . $configType . '/option');
            }
        }

        return $content
            ->header('看图筛选条件管理')
            ->breadcrumb(
                ['text' => '看图筛选条件']
            )
            ->body($tab->render());
    }

    /**
     * 增加选项
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function create(Request $request, Content $content)
    {
        $form = new Form([]);

        $form->hidden('id');

        $list = [];

        foreach (self::$config as $type => $row) {
            if ($type != 5) {//作者
                $list[$type] = $row['name'];
            }
        }
        $form->select('type', '选项类别')->options($list)->required();
        $form->text('keyword', '关键字')->required();

        $form->action('/admin/search/select/save');

        return $content->header('添加关键词')->breadcrumb(
            ['text' => '看图筛选条件管理', 'url' => url('/admin/search/select/index')],
            ['text' => '添加关键词'])
            ->row($form->render());
    }

    /**
     * 保存
     * @param Request $request
     * @param Content $content
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function save(Request $request, Content $content)
    {
        $data = $request->all();
        $type = $data['type'];
        $name = $data['keyword'];

        //处理需要的数据
        $ids = array_column(self::$config[$type]['options'], 'options_id');
        $sorts = array_column(self::$config[$type]['options'], 'sort');
//        $optionsId = max($ids) + 1;
//        $sort = max($sorts) + 1;

        //组合入库数据
        $add = [
            'options_id' =>  max($ids) + 1,
            'type_id' => $type,
            'name' => $name,
            'value' => $name,
            'sort' => max($sorts) + 1,
            'admin_id' => Admin::user()->id,
            'add_time' => date('Y-m-d H:i:s')
        ];
        $res = SelectParamsOptions::addData($add);
        if ($res) {
            //清除缓存
            $this->delConfigV2();
        }
//        $ids = array_column(self::$config[$type]['options'], 'id');
//        $id = max($ids) + 1;
//        $this->delConfigV2();

//        self::$config[$type]['options'][] = ['id' => $id, 'value' => $name, 'name' => $name];
//        $this->saveConfig(self::$config);
        return redirect(url('/admin/search/select/index'))->with(compact('success'));
    }

    /**
     * 类型排序
     * @param Request $request
     * @param Content $content
     */
    public function sortType(Request $request, Content $content)
    {
        $data = $request->all();
        $sort = $data['sort'];
//---------
        $admin_id = Admin::user()->id;
        photoSelectParams::sortType($sort, $admin_id);
        //清除缓存
        $this->delConfigV2();
//--------
//        self::$config = [];
//        $config = photoSelectParams::getConfig();
//        foreach ($sort as $type => $value) {
//            self::$config[$type] = $config[$type];
//        }
//        $this->saveConfig(self::$config);
    }

    /**
     * 选项排序
     * @param Request $request
     * @param Content $content
     * @param $type
     */
    public function sortKey(Request $request, Content $content, $type)
    {
        $data = $request->all();
        $sort = $data['sort'];
        //----------
        $admin_id = Admin::user()->id;
        photoSelectParams::sortOptions($type, $sort, $admin_id);
        //清除缓存
        $this->delConfigV2();
        //-------
//        self::$config[$type]['options'] = [];
//        $config = photoSelectParams::getConfig();
//        $options = array_column($config[$type]['options'], null, 'id');
//        foreach ($sort as $id => $value) {
//            self::$config[$type]['options'][] = $options[$id];
//        }
//        $this->saveConfig();
    }

    /**
     * 删除选项
     * @param Request $request
     * @param Content $content
     * @param $type
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function del(Request $request, Content $content, $type, $id)
    {
        //处理数据库状态

        self::$config = [];
        $admin_id = Admin::user()->id;
        photoSelectParams::updateOptionsById($id, $admin_id);
        photoSelectParams::sortByType($type);
        //清除缓存
        $this->delConfigV2();
//        $config = photoSelectParams::getConfig();
//        foreach ($config as $typeVal => $value) {
//            $varArr['name'] = $value['name'];
//            $varArr['key'] = $value['key'];
//            $varArr['options'] = [];
//            if ($typeVal == $type) {
//                foreach ($value['options'] as $val) {
//                    if ($val['id'] != $id) {
//                        $varArr['options'][] = $val;
//                    }
//                }
//            } else {
//                $varArr['options'] = $value['options'];
//            }
//            self::$config[$typeVal] = $varArr;
//        }
//        $this->saveConfig();
        return redirect(url('/admin/search/select/index'))->with(compact('success'));
    }

    private function saveConfig()
    {
        photoSelectParams::saveConfig(self::$config);
    }

    /**
     * 清理缓存
     */
    private function delConfigV2()
    {
        photoSelectParams::delConfigV2();
    }

    /**
     * 绑定关联词
     * @param Request $request
     * @param Content $content
     * @param $type
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function relation(Request $request, Content $content, $type, $id)
    {
        $params = $request->input('list', []);
        $admin_id = Admin::user()->id;
        $list = self::$config;
        unset($list[$type]);
        unset($list[photoSelectParams::TYPE_SCOPE_AUTH]);

        $aOptions = photoSelectParams::formatRelationSelect($list);
        $aOptions = array_column($aOptions, null, 'id');

        $arr = [];
        foreach ($params as $key => $oid) {
            $typeId = $aOptions[$oid]['type_id'];
            $arr[$typeId]['type'] = $typeId;
            $arr[$typeId]['name'] = $list[$typeId]['name'];

            $data['name'] = $aOptions[$oid]['name'];
            $data['key'] = $list[$typeId]['key'];;
            $data['id'] = $oid;
            $data['sort'] = $aOptions[$oid]['sort'];
            $arr[$typeId]['option_list'][] = $data;
        }
        $create = json_encode(array_values($arr));
        $res = photoSelectParams::updateOptionsRelation($id, $admin_id, $create);
        if ($res) {
            $this->delConfigV2();
            return response()->json([
                'status' => true,
                'message' => "关联词添加成功",
            ]);
        }
        return response()->json([
            'status' => false,
            'message' => "关联词添加失败",
        ]);
    }

}